// 全局通用正则表达式
window.pattern = {
	// 身份证号
	idCard: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9X]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
	// 手机号
	phone: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
	// 统一社会信用代码
	license: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/,
	// 密码
	password: /^(?=.*[A-Za-z!#@$%^&*])(?=.*\d)[A-Za-z!#@$%^&*\d]{8,}$/,
	// 正整数
	positiveInteger: /^[1-9]+[0-9]*]*$/
}
var pubsub = (function() {
	var q = {}
	topics = {},
		subUid = -1;
	//发布消息
	q.publish = function(topic, args, callback) {
		if (!topics[topic]) {
			return;
		}
		var subs = topics[topic],
			len = subs.length;
		while (len--) {
			if (callback) {
				return callback(subs[len].func(topic, args));
			} else {
				subs[len].func(topic, args)
			}


		}

	};
	//订阅事件
	q.subscribe = function(topic, func) {
		topics[topic] = topics[topic] ? topics[topic] : [];
		var token = (++subUid).toString();
		topics[topic].push({
			token: token,
			func: func
		});
		return token;
	};
	return q;
	//取消订阅就不写了，遍历topics，然后通过保存前面返回token，删除指定元素
})(window);

layer = layer;
common = {

	countZoom: function(lonArr, latArr) {
		var use_lon = lonArr[0] - lonArr[1]
		var use_lat = latArr[0] - latArr[1]
		if (use_lon / 20 >= use_lat / 9) {
			return Math.floor(19 - Math.log(200 * use_lon) / Math.log(2)) > 19 ? 19 : Math.floor(
				19 - Math.log(200 * use_lon) / Math.log(2)) < 11 ? 11 : Math.floor(19 - Math
				.log(200 * use_lon) / Math.log(2))
		} else {
			return Math.floor(19 - Math.log(444 * use_lat) / Math.log(2)) > 19 ? 19 : Math.floor(
				19 - Math.log(444 * use_lat) / Math.log(2)) < 11 ? 11 : Math.floor(19 - Math
				.log(444 * use_lat) / Math.log(2))
		}
	},
	getQueryStringObj() {
		var qs = location.search.substr(1), // 获取url中"?"符后的字串  
			args = {}, // 保存参数数据的对象
			items = qs.length ? qs.split("&") : [], // 取得每一个参数项
			item = null,
			len = items.length;
		for (var i = 0; i < len; i++) {
			item = items[i].split("=");
			var name = decodeURIComponent(item[0]),
				value = decodeURIComponent(item[1]);
			if (name) {
				args[name] = value;
			}
		}
		return args;
	},
	/*
	 设置map对象
	 */
	getRandom: function(mi, mx) {
		return Math.floor(mi + Math.random() * (mx - mi))
	},
	/*
	Token
	 */
	getTokenKey: function() {
		var name = location.pathname
		return location.host + location.pathname.substr(1, location.pathname.substr(1, location
			.pathname.length).indexOf("/"));
	},
	/*two=2代表双数组*/
	arrayString: function(data, two) {
		var str = "";
		if (two == 1) {
			for (var i = 0; i < data.length; i++) {
				if (i % 2 == 0) {
					str += data[i] + " ";
				} else {
					str += data[i] + ",";
				}
			}
		} else if (two == 2) {
			for (var i = 0; i < data.length; i++) {
				str += data[i][0] + " " + data[i][1] + ","
			}
		} else if (two == 3) {
			var dat = data.split(",");
			for (var i = 0; i < dat.length; i++) {
				dat[i] = dat[i].split(" ");
				dat[i][0] = Number(dat[i][0]);
				dat[i][1] = Number(dat[i][1]);
			}
			return dat
		}
		return str.substring(0, str.lastIndexOf(','));
	},
	/* data:  class类名
	 *title： 为true只改变层级,初始化和点击title时使用
	 */
	getImgToBase64: function(url, callback) {
		var cao = window.URL.createObjectURL(url)
		var canvas = document.createElement('canvas'),
			ctx = canvas.getContext('2d'),
			img = new Image;
		img.crossOrigin = 'Anonymous';
		img.onload = function() {
			canvas.height = img.height;
			canvas.width = img.width;
			ctx.drawImage(img, 0, 0);
			var dataURLes = canvas.toDataURL(url.type);
			var type = dataURLes.substring(dataURLes.indexOf(",") + 1, dataURLes.length);
			callback({
				img: dataURLes,
				data: type
			});
			canvas = null;
		};
		img.src = cao;
	},

	/*说话*/
	speak: function(name, yinl, speed) {
		var name = encodeURI(name);
		$.ajax({
			type: "GET",
			url: alluse.yuyin + "cz0-yvyin/makeWav/" + yinl + "/" + speed + "/" + name,
			beforeSend: function() {

			},
			success: function(data, status, xhr) {
				$("#embedPlay").remove();
				var strEmbed = '<embed id="embedPlay" src="' + alluse.yuyin +
					"cz0-yvyin/" + data +
					'.wav" autostart="true" hidden="true" loop="false"></embed>';
				$("body").append(strEmbed);
				try {
					var embed = $("#embedPlay")[0];
					embed.volume = 0;
					embed.play();
				} catch (e) {
					common.consoleLogs(e)
				}

			},
			error: function(xhr, error, exception) {

			}
		});
	},

	/*从数组中获取字段的集合*/
	GetObjectcColumn: function(obj, column) {
		var temp = []
		if (obj) {
			for (var i = 0; i < obj.length; i++) {
				temp.push(obj[i][column]);
			}
		}

		return temp;
	},
	/*删除元素*/
	deleteDom: function(data) {
		data.fadeTo("slow", 0.01, function() { //fade
			data.slideUp("slow", function() { //slide up
				data.remove(); //then remove from the DOM
			});
		});
		return data;
	},
	msgAll: function(avl, data, callback) {
		var temp = {
			success: function(tar, index) {
				if (callback) {
					callback(tar, index);
				}
				tar.append(
					"<div class='leftBG'></div><div class='rightBG'></div><div class='leftBBG'></div><div class='rightBBG '></div>"
				)
			}
		}
		if (data) {
			var tar = $.extend(temp, data);
		}
		layer.msg(avl, tar);
	},
	lodding: function(tar) {
		tar.append('<section>' +
			'<div class="loader loader-18">' +
			' <div class="css-star star1"></div>' +
			'<div class="css-star star2"></div>' +
			'<div class="css-star star3"></div>' +
			'<div class="css-star star4"></div>' +
			' <div class="css-star star5"></div>' +
			' <div class="css-star star6"></div>' +
			'<div class="css-star star7"></div>' +
			'<div class="css-star star8"></div>' +
			' </div>' +
			' </section>');
	},
	//使用如下方法可以将json的key值转为大写，小写同理
	upperJSONKey: function(jsonObj) {
		for (var key in jsonObj) {
			jsonObj[key.toUpperCase()] = jsonObj[key];
			delete(jsonObj[key]);
		}
		return jsonObj;
	},
	//使用如下方法可以将json的key值转为小写
	LowerJSONKey: function(jsonObj) {
		for (var key in jsonObj) {
			jsonObj[key.toLowerCase()] = jsonObj[key];
			delete(jsonObj[key]);
		}
		return jsonObj;
	},
	/*获取InfoTemplate*/
	getInfoTemplate: function(fdata) {
		var template = {};
		common._ajaxGet("lib/util/popup/popcontent/" + fdata.name + ".json", "", function(da) {
			if (da != 2) {
				var temp = da.fields;
				if (da.img) {
					var table =
						'<table style="width: 239px; float: left; margin-left: 10px;" lay-filter="parse-table-demo"> <tbody> ';
				} else {
					var table = '<table lay-filter="parse-table-demo"> <tbody> ';
				}
				for (var i = 0; i < temp.length; i++) {
					table = table + '<tr> <td>' + temp[i].alias + ':</td> <td>${' + temp[i]
						.name + '}</tr>'
				}
				table = table + '</tbody> </table>'
				if (da.img) {
					var te =
						'<div class="layui-fluid c" style="position: absolute; bottom: 0; right: 25px;margin-top: 10px;"> '
				} else {
					var te = '<div class="layui-fluid c" style="margin-top: 10px;"> '
				}
				if (da.buttons != undefined) {
					for (var i = 0; i < da.buttons.length; i++) {
						var bt = da.buttons[i]
						if (i == 0) {
							te = te +
								'<button class="layui-btn layui-btn-primary" addType="' + bt
								.type + '" >' + bt.name +
								'</button>'
						} else {
							te = te + '<button class="layui-btn"  addType="' + bt.type +
								'">' + bt.name + '</button>'

						}
					}
				}
				table = table + te + '</div> ';
				if (da.img) {
					var img = '<img style="float:left"  src="${' + da.img + '}"/>';
					table = img + table;
				}
				template.title = da.title;
				template.table = table;
			}
		}, false)

		return template;
	},
	//浏览器地址栏根据参数的名字就行获取参数值
	GetQueryString: function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return decodeURI(r[2]);
		return null;
	},

	/* 检测是不是中文 超过四位数也不是姓名 */
	xingming: function(name) {

		var pattern = new RegExp("[\u4E00-\u9FA5]+");

		if (pattern.test(name) && name.length < 5 && name.length > 1) {
			return true

		} else {
			return false;
		}
	},
	/* 检测admin */
	isAdmin: function(name) {
		if (name == "admin" || name == "bdmap") {
			return true;
		} else {
			return false;
		}
	},
	/*检测身份证*/
	isIdCard: function(name) {
		var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		return reg.test(name);
	},
	/*检测手机号*/
	isPhoneNo: function(phone) {
		var pattern = /^1[3456789]\d{9}$/;
		return pattern.test(phone);
	},
	/*检测车牌*/
	isLicenseNo: function(str) {
		str = str.toUpperCase();
		return /(^[\u4E00-\u9FA5]{1}[A-Z0-9]{6}$)|(^[A-Z]{2}[A-Z0-9]{2}[A-Z0-9\u4E00-\u9FA5]{1}[A-Z0-9]{4}$)|(^[\u4E00-\u9FA5]{1}[A-Z0-9]{5}[挂学警军港澳]{1}$)|(^[A-Z]{2}[0-9]{5}$)|(^(08|38){1}[A-Z0-9]{4}[A-Z0-9挂学警军港澳]{1}$)/
			.test(str);
	},

	/*	去除没用的字段
		请求格式
		{
			name:"213213",
			password:""
		}
		返回
		{
			name:"213213"
		}
	*/
	deleteObj: function(obj) {
		for (var key in obj) {
			if (obj[key].trim() == "") {
				delete obj[key]
			}
		}
		return obj;
	},
	/* =data.sort(common.compare('train_date'))
		更具数组字段排序
		请求格式:[{num:2},{num:1}]
		返回格式:[{num:1},{num:2}]
	 */
	compare: function(property) {
		return function(a, b) {
			var value1 = a[property];
			var value2 = b[property];
			return value1 - value2;
		}
	},

	/*
		获取网站目录
	 */
	getRootPath: function() {
		if (window["context"] == undefined) {
			if (!window.location.origin) {
				window.location.origin = window.location.protocol + "//" + window.location
					.hostname + (window.location.port ?
						':' +
						window.location.port : '');
			}
			window["context"] = location.origin + "/V6.0";
		}
		var pathRegex = new RegExp(/\/[^\/]+$/);
		var locationPath = location.pathname.replace(pathRegex, '');
		return location.origin + locationPath;
	},
	/*
	 加载css资源文件,已做排重
	 */
	loadCssResource: function(path) {
		var state = false;
		$('link[type="text/css"]').each(function(ev) {
			if (this.name != "" && this.name === path) {
				var tmpName = this.name;
				state = true;
				return false;
			}
		});
		if (!state) {
			var cssUrl = path;
			var link = document.createElement("link");
			link.type = "text/css";
			link.rel = "stylesheet";
			link.name = cssUrl;
			link.href = cssUrl;
			document.getElementsByTagName("head")[0].appendChild(link);
		}
		return "ok";
	},
	/*
	 加载js资源文件,已做排重
	 */
	loadScriptResource: function(path) {
		if (path.length > 0) {
			for (var i = 0; i < path.length; i++) {
				var state = false;
				$('script[type="text/javascript"]').each(function(ev) {
					if (this.name != "" && this.name === path[i]) {
						var tmpName = this.name;
						state = true;
						return false;
					}
				});
				if (!state) {
					var scriptUrl = path[i];
					var script = document.createElement("script");
					script.type = "text/javascript";
					script.name = path[i];
					script.src = scriptUrl;
					document.head.appendChild(script);
				}
			}
		}
		return "ok";
	},
	/*
	 输出log日志到控制台
	 */
	consoleLogs: function(content) {
		console.log(content);
	},
	/*
	 获取当前时间
	 */
	getTimeString: function(timeType, DateTime) {
		var str = "";
		if (!DateTime) {
			var tmpDate = new Date();
		}
		switch (timeType) {
			//获取年月日
			case "yyyy/mm/dd":
				var year = tmpDate.getFullYear();
				var month = (tmpDate.getMonth() + 1) > 9 ? (tmpDate.getMonth() + 1).toString() :
					'0' + (tmpDate.getMonth() +
						1);
				var date = tmpDate.getDate() > 9 ? tmpDate.getDate().toString() : '0' + tmpDate
					.getDate();
				str = year + "/" + month + "/" + date;
				break;
				//获取前2天日期
			case "-2":
				var tmpDate = new Date(tmpDate);
				tmpDate.setDate(tmpDate.getDate() - 2);

				var year = tmpDate.getFullYear();
				var month = (tmpDate.getMonth() + 1) > 9 ? (tmpDate.getMonth() + 1).toString() :
					'0' + (tmpDate.getMonth() +
						1);
				var date = tmpDate.getDate() > 9 ? tmpDate.getDate().toString() : '0' + tmpDate
					.getDate();
				str = year + "-" + month + "-" + date + " 00:00:00";
				break;
			case "yyyy-mm-dd":
				var year = tmpDate.getFullYear();
				var month = (tmpDate.getMonth() + 1) > 9 ? (tmpDate.getMonth() + 1).toString() :
					'0' + (tmpDate.getMonth() +
						1);
				var date = tmpDate.getDate() > 9 ? tmpDate.getDate().toString() : '0' + tmpDate
					.getDate();
				str = year + "-" + month + "-" + date;
				break;
			case "yyyy-mm":
				var year = tmpDate.getFullYear();
				var month = (tmpDate.getMonth() + 1) > 9 ? (tmpDate.getMonth() + 1).toString() :
					'0' + (tmpDate.getMonth() +
						1);
				var date = tmpDate.getDate() > 9 ? tmpDate.getDate().toString() : '0' + tmpDate
					.getDate();
				str = year + "-" + month;
				break;
			case "yyyy-m-d":
				var year = tmpDate.getFullYear();
				var month = (tmpDate.getMonth() + 1).toString();
				var date = tmpDate.getDate().toString();
				str = year + "-" + month + "-" + date;
				break;
			case "yyyy-m-d hh:mm":
				var year = tmpDate.getFullYear();
				var month = (tmpDate.getMonth() + 1);
				var date = tmpDate.getDate();
				var hour = tmpDate.getHours() > 9 ? tmpDate.getHours().toString() : '0' + tmpDate
					.getHours();
				var minute = tmpDate.getMinutes() > 9 ? tmpDate.getMinutes().toString() : '0' +
					tmpDate.getMinutes();
				str = year + "-" + month + "-" + date + " " + hour + ":" + minute;
				break;
			case "yyyy/mm/dd hh:mm:ss":
				var year = tmpDate.getFullYear();
				var month = tmpDate.getMonth() >= 9 ? tmpDate.getMonth() + 1 : "0" + (tmpDate
					.getMonth() + 1);
				var date = tmpDate.getDate() >= 9 ? tmpDate.getDate() : "0" + (tmpDate.getDate());
				var hour = tmpDate.getHours() > 9 ? tmpDate.getHours().toString() : '0' + tmpDate
					.getHours();
				var minute = tmpDate.getMinutes() > 9 ? tmpDate.getMinutes().toString() : '0' +
					tmpDate.getMinutes();
				var seconds = tmpDate.getSeconds() > 9 ? tmpDate.getSeconds().toString() : '0' +
					tmpDate.getSeconds();
				str = year + "/" + month + "/" + date + " " + hour + ":" + minute + ":" + seconds;
				break;
			case "Date":
				var year = DateTime.getFullYear();
				var month = DateTime.getMonth() >= 9 ? DateTime.getMonth() + 1 : "0" + (DateTime
					.getMonth() + 1);
				var date = DateTime.getDateTime() >= 9 ? DateTime.getDateTime() : "0" + (DateTime
					.getDateTime());
				var hour = DateTime.getHours() > 9 ? DateTime.getHours().toString() : '0' + DateTime
					.getHours();
				var minute = DateTime.getMinutes() > 9 ? DateTime.getMinutes().toString() : '0' +
					DateTime.getMinutes();
				var seconds = DateTime.getSeconds() > 9 ? DateTime.getSeconds().toString() : '0' +
					DateTime.getSeconds();
				str = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + seconds;
				break;
				//当前时间
			case "yyyy-mm-dd hh:mm:ss":
				var year = tmpDate.getFullYear();
				var month = tmpDate.getMonth() >= 9 ? tmpDate.getMonth() + 1 : "0" + (tmpDate
					.getMonth() + 1);
				var date = tmpDate.getDate() >= 9 ? tmpDate.getDate() : "0" + (tmpDate.getDate());
				var hour = tmpDate.getHours() > 9 ? tmpDate.getHours().toString() : '0' + tmpDate
					.getHours();
				var minute = tmpDate.getMinutes() > 9 ? tmpDate.getMinutes().toString() : '0' +
					tmpDate.getMinutes();
				var seconds = tmpDate.getSeconds() > 9 ? tmpDate.getSeconds().toString() : '0' +
					tmpDate.getSeconds();
				str = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + seconds;
				break;
				//当前时间下一天
			case "yyyy-m-d next":
				var year = tmpDate.getFullYear();
				var month = (tmpDate.getMonth() + 1);
				var date = tmpDate.getDate() + 1;
				str = year + "-" + month + "-" + date;
				break;
				//获取当前月份的前月
			case "yyyy年m月 pre":
				var year = tmpDate.getFullYear();
				tmpDate.setMonth(Number(tmpDate.getMonth()) - 1); //统计上月
				var month = (tmpDate.getMonth() + 1);
				var date = tmpDate.getDate() + 1;
				str = year + "年" + month + "月";
				break;
				//获取当前月份的前月
			case "mm pre":
				var year = tmpDate.getFullYear();
				tmpDate.setMonth(Number(tmpDate.getMonth()) - 1); //统计上月
				var month = (tmpDate.getMonth() + 1) > 9 ? (tmpDate.getMonth() + 1) : '0' + (tmpDate
					.getMonth() + 1);
				str = month + "月";
				break;
				//获取星期几
			case "week":
				var tmpday = tmpDate.getDay(); //注:0-6对应为星期日到星期六
				switch (tmpday) {
					case 0:
						str = "星期日";
						break;
					case 1:
						str = "星期一";
						break;
					case 2:
						str = "星期二";
						break;
					case 3:
						str = "星期三";
						break;
					case 4:
						str = "星期四";
						break;
					case 5:
						str = "星期五";
						break;
					case 6:
						str = "星期六";
						break;
					default:
						str = "系统错误！"
				}
				break;
				//获取时分秒
			case "hh:mm:ss":
				var hour = tmpDate.getHours() > 9 ? tmpDate.getHours().toString() : '0' + tmpDate
					.getHours();
				var minute = tmpDate.getMinutes() > 9 ? tmpDate.getMinutes().toString() : '0' +
					tmpDate.getMinutes();
				var seconds = tmpDate.getSeconds() > 9 ? tmpDate.getSeconds().toString() : '0' +
					tmpDate.getSeconds();
				str = hour + ":" + minute + ":" + seconds;
				break;
				//获取时
			case "hh":
				var hour = tmpDate.getHours() > 9 ? tmpDate.getHours().toString() : '0' + tmpDate
					.getHours();
				str = hour;
				break;
				//获取秒
			case "ss":
				var ss = tmpDate.getMilliseconds();
				str = ss;
				break;
				//获取前30天
			case "30":
				var date1 = new Date();
				var date2 = new Date(date1);
				date2.setDate(date1.getDate() - 30);
				var year = date2.getFullYear();
				var month = date2.getMonth() >= 9 ? date2.getMonth() + 1 : "0" + (date2.getMonth() +
					1);
				var date = date2.getDate() >= 9 ? date2.getDate() : "0" + (date2.getDate());
				str = year + "-" + month + "-" + date;
				break;
			case "7":
				var date1 = new Date();
				var date2 = new Date(date1);
				date2.setDate(date1.getDate() - 7);
				var year = date2.getFullYear();
				var month = date2.getMonth() >= 9 ? date2.getMonth() + 1 : "0" + (date2.getMonth() +
					1);
				var date = date2.getDate() >= 9 ? date2.getDate() : "0" + (date2.getDate());
				str = year + "-" + month + "-" + date;
				break;
			default:
				break;
		}
		return str;
	},
	getmenu: function(tar) {
		var flf = false
		var menu = config.user.menu;
		for (var i = 0; i < menu.length; i++) {
			var name = menu[i].menuName
			if (name == tar) {
				flf = true
			}

		}
		return flf
	}

};
//全局的ajax访问，处理ajax清求时异常
$.ajaxSetup({
	beforeSend: function(request, setting) {
		AssembleTheUrl(request, setting)
	}
});

function AssembleTheUrl(request, setting) {
	var tar = setting.url
	tar = setting.url.split("//")[1]
	var tt = tar.indexOf("?")
	var one = tar.indexOf("/");
	if (tt == -1) {
		setAuthorization(request, tar.substring(one, tar.length))
	} else {
		setAuthorization(request, tar.substring(one, tt))
	}

}

function setAuthorization(request, setting) {
	var flg = true;
	for (var i = 0; i < AuthorizationFilter.length; i++) {
		if (setting == AuthorizationFilter[i]) {
			flg = false
			break
		} else {
			flg = true
		}

	}
	if (flg) {
		request.setRequestHeader("Authorization", "Bearer " + $.cookie(common.getTokenKey()));
	}
}
$(document).ajaxComplete(function(evt, request, settings) {
	if (request.responseJSON) {
		var data = request.responseJSON.code
		if (data == "401") {
			window.location.href = common.getRootPath() + "/login/login.html";
		} else if (data == "500") {
			pubsub.publish("$msgError", "接口" + settings.url + request.responseJSON.msg)

		} else if (data == "403") {
			pubsub.publish("$msgError", "接口" + settings.url + request.responseJSON.msg)
		}

	}
});
Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1)
	}
}

function hasPermission(permission) {
	return config.user.permissions.indexOf(permission) !== -1
}